//
//  QRcodeRecognitionView.m
//  FuncFanc
//
//  Created by careate-hubing on 2021/9/14.
//  Copyright © 2021 huhu. All rights reserved.
//

#import "QRcodeRecognitionView.h"
#import <WebKit/WebKit.h>

@interface QRcodeRecognitionView ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>

@property (nonatomic,strong)WKWebView *localWebView;

@property (nonatomic,strong) NSString *url;

@property (nonatomic,strong) NSTimer *timer;

@property (nonatomic,strong) UIScrollView *scroll;

@end


@implementation QRcodeRecognitionView

-(instancetype)initWithFrame:(CGRect)frame andUrlstr:(NSString *)urlStr{
    if (self = [super initWithFrame:frame]) {
        _url = urlStr;
        [self createWebview];
        [self startTimer];
    }
    return self;
}

-(void)startTimer
{
    __weak typeof(self) ws = self;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:NO block:^(NSTimer * _Nonnull timer) {
       
        [self screenShotAndRecognizer];
//        if (ws.recognitionBlock) {
//            ws.recognitionBlock(@"超时");
//        }
        [ws removeFromSuperview];
    }];
}

-(void)dealloc{
    [self stopTimer];
}

-(void)stopTimer
{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

-(void)createWebview
{
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = userContentController;
    if (@available (iOS 14.0,*)) {
        config.limitsNavigationsToAppBoundDomains = YES;
    }
    // 设置偏好设置 (都是默认的，需要改的时候来改)
    config.preferences = [[WKPreferences alloc] init];
    // 默认为0
    config.preferences.minimumFontSize = 10;
    // 默认认为YES
    config.preferences.javaScriptEnabled = YES;
    
    // 在iOS上默认为NO，表示不能自动通过窗口打开
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    _localWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height) configuration:config];
    _localWebView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
    _localWebView.scrollView.bounces = NO;
    _localWebView.UIDelegate = self;
    _localWebView.navigationDelegate = self;
    _localWebView.hidden = YES;
    [self insertSubview:_localWebView atIndex:0];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_url]];
    [_localWebView loadRequest:request];
    
//    _scroll = (UIScrollView *)self.localWebView;
    
    
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
//    [self stopTimer];
//    [self screenShotAndRecognizer];
}

-(void)screenShotAndRecognizer{
    _localWebView.hidden = NO;
    UIScrollView *scroll = (UIScrollView *)self.localWebView;
    _scroll = scroll;
    CGRect frame = _scroll.frame;
    CGRect frame1 = _scroll.frame;
    CGSize contentSize = self.localWebView.scrollView.contentSize;
    frame.size.height = self.localWebView.scrollView.contentSize.height;
    frame.size.width = self.localWebView.scrollView.contentSize.width;
    _scroll.frame = frame;
        
    UIGraphicsBeginImageContextWithOptions(contentSize,YES,0);
    [self.localWebView.scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * tempImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRef imageRef = tempImage.CGImage;
    _localWebView.hidden = YES;
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];
    NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:imageRef]];
    
    if (features.count > 0) {
        CIQRCodeFeature *feature = [features objectAtIndex:0];
        NSString *scannedResult = feature.messageString;
        DebugLog(@"%@",scannedResult);
        
        if (self.recognitionBlock) {
            self.recognitionBlock(scannedResult);
        }
        [self removeFromSuperview];
    }
    else
    {
        if (self.recognitionBlock) {
            self.recognitionBlock(@"未识别到二维码");
        }
        UIImage *finishImage = [[UIImage alloc]initWithCGImage:imageRef];

        UIImageWriteToSavedPhotosAlbum(finishImage, nil, nil, nil);

        [self removeFromSuperview];
    }

    _scroll.frame = frame1;
}


- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    if (self.recognitionBlock) {
        self.recognitionBlock(@"页面加载失败");
    }
    [self removeFromSuperview];
}

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
    if (self.recognitionBlock) {
        self.recognitionBlock(@"进程被终止");
    }
    [self removeFromSuperview];
}


@end
